package team.fivez.defaultmanage.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import team.fivez.defaultmanage.dao.ApproverDao;
import team.fivez.defaultmanage.domain.Approver;

import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

@Component
public class ApproverService {


    private final ApproverDao approverDao;

    @Autowired
    public ApproverService(ApproverDao approverDao) {
        this.approverDao = approverDao;
    }


    //审核人登录，0成功，1失败
    public int login(Approver approver) throws NoSuchAlgorithmException {
        //查找用户是否存在
        Integer count = approverDao.getCountByApproverAccount(approver.getApproverAccount());
        if(count !=1){
            return 1;//不存在该审核人
        }
        Approver approverFromDB = approverDao.getApproverByApproverAccount(approver.getApproverAccount());
        //将密码加密判断
        MessageDigest md = MessageDigest.getInstance("SHA");
        byte[] digest = md.digest(approver.getApproverPassword().getBytes());
        BigInteger bigInteger = new BigInteger(1, digest);
        String password_new = bigInteger.toString(16);

        if (password_new.equals(approverFromDB.getApproverPassword())){
            return 0;
        }
        else return 1;

    }

    //审核人注册，0成功，1失败
    public int register(Approver approver) throws NoSuchAlgorithmException {
        //查找用户是否存在
        Integer count = approverDao.getCountByApproverAccount(approver.getApproverAccount());
        if(count ==1){
            return 1;//存在该审核人
        }
        //将密码进行加密
        MessageDigest md = MessageDigest.getInstance("SHA");
        byte[] digest = md.digest(approver.getApproverPassword().getBytes());
        BigInteger bigInteger = new BigInteger(1, digest);
        String password_new = bigInteger.toString(16);

        //设置加密密码
        approver.setApproverPassword(password_new);

        int i= approverDao.insertApprover(approver);

        if (i==1){
            return 0;
        }
        else return 1;

    }



}
